package foo.bar.wiki.web.extension;

import net.sourceforge.stripes.controller.Interceptor;
import net.sourceforge.stripes.controller.ExecutionContext;
import net.sourceforge.stripes.controller.Intercepts;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.integration.spring.SpringBean;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.transaction.TransactionStatus;
import foo.bar.wiki.web.action.TransactionStatusAware;

/**
 * @author tmjee
 * @version $Date$ $Id$
 */
@Intercepts({LifecycleStage.ActionBeanResolution,LifecycleStage.CustomValidation, LifecycleStage.BindingAndValidation})
public class TransactionStatusAwareInterceptor implements Interceptor {

    private TransactionTemplate transactionTemplate;

    public Resolution intercept(ExecutionContext executionContext) throws Exception {
        Resolution resolution = executionContext.proceed();
        if (executionContext.getActionBean() instanceof TransactionStatusAware) {
                TransactionStatus transactionStatus = (TransactionStatus)
                                        TransactionSynchronizationManager.getResource(transactionTemplate);
                ((TransactionStatusAware)executionContext.getActionBean()).setCurrentTransactionStatus(transactionStatus);
        }
        else {
            throw new RuntimeException("ActionBean ["+executionContext.getActionBean()+"] is not TransactionStatusAware");
        }
        return resolution;
    }


    @SpringBean("transactionTemplate")
    public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
        this.transactionTemplate = transactionTemplate;
    }

}
